<template>
<!-- Main content -->
<div>
    <div class="row">
        <div class="col-xs-12">
            <theme-box title="商品类型维护">
              <form class="form-inline" @submit.prevent v-el:form>
                  <form-select title="商户号" :up-table="true" :sreach="true" name="mchtId" :options="branchList"></form-select>
                  <form-input title="商品类型名称"  name="typeName" :up-table="true"></form-input>
                  <button type="reset" @click="reset" class="btn btn-warning pull-right">重置</button>
                  <v-button theme="primary" @click="search" class="pull-right">查询</v-button>
              </form>
                <table class="table table-bordered table-striped" style="width:100%" v-el:table></table>
            </theme-box>
        </div>

        <!-- /.col -->
    </div>
    <modal-container title="修改" v-el:modal v-ref:modal class="edit-modal" theme="small_window">
        <form @submit.prevent @reset.prevent v-el:mform>
            <div class="modal-body">
                <table-modal :item="item" :columns-set="columnsSet" :columns-num="1"></table-modal>
            </div>
            <div class="modal-footer">
                <v-button class="pull--left" data-dismiss="modal" @click="resetBindDrag">关闭</v-button>
                <v-button theme="primary" type="submit">保存</v-button>
            </div>
        </form>
    </modal-container>
    <!-- /.row -->
</div>
<!-- /.content -->
</template>

<style lang="less" scoped>
.form-inline .btn+.btn {
    margin-right: 10px;
}
.form-inline .form-group+.form-group {
    margin-left: 20px;
}
</style>
<style>
    .edit-modal tr td:first-child{
     width:24%
 }
</style>
<script>
import {
    dateTime,
    createDataTable
} from 'ui/collections/general.js'
var serialize = require('form-serialize');

var dataTable;
var columnsSet;
export default {
    data: () => ({
        _array:[],
        item: {},
        columnsSet: [],
        branchList: [],
        updTypeName:[]
    }),
    methods: {
        //还原弹出框位置
        resetBindDrag() {
            this.$refs.modal._resetBindDrag();
        },
        //查询按钮
        search: function() {
            dataTable.ajax.reload();
        },
        //重置按钮
        reset: function() {
            $(".form-inline")[0].reset();
            dataTable.ajax.reload();
        },
        getBranch(data) {
    			let self = this;
    		  var mchtId = JSON.parse(localStorage.getItem("id_token")).mchtId
    			self.$post({
    				url: "/api/v2" + projectName_Url + "/list/mcht/"+ mchtId,
    				method:"GET"
    			}).then(response => {
    				let list = response.content.info;
                    if(list.length == 1){
                        list.unshift({key:"商户",value:""});
                        self.$set("branchList", list);
//                        self.mchtIdValue = list[0].value
                    }else{
                        list.unshift({key:"所有商户",value:""});
                        self.$set("branchList", list);
                        self.mchtIdValue = list[0].value
                    }
    			}, error => {});
    		}
    },
    created() {
        //主页面datatable所用数组
        columnsSet = [{
            title: "商户号",
            data: "mchtId",
            visible:false,
            readonly: true,
            className:"operate"
        },{
            title: "商户名称",
            data: "mchtName",
            edit: true,
            readonly: true,
            className:"operate"
        },{
            title: "商品类型号",
            data: "typeId",
            edit: true,
            readonly: true,
            className:"operate"
        },{
            title: "上级商品类型",
            data: "typeUpdId",
            visible:false,
            className:"operate"
        },{
            title: "上级商品类型",
            data: "updTypeName",
            className:"operate",
            render:function(data){
              return (data == '') ? "无" : data
            }
        },{
            title: "商品类型名称",
            data: "typeName",
            edit: true,
            className:"operate"
        },{
            title: "相关操作",
            className: "operate",
            width: "120px",
            render: function(value, type, row) {
                return `
                    <button type="button" class="btn btn-primary btn-sm edit">修改</button>
                    <button type="button" class="btn btn-danger btn-sm delete">删除</button>
                      `
            }
        }];
    },
    ready: async function() {
        dateTime({
            format: "yyyy-mm-dd",
            minView: "2"
        })
        this.$set("columnsSet", columnsSet)
        var self = this;
        self.getBranch();
        //创建dataTable
          dataTable = $(this.$els.table).DataTable({
            "columns": this.columnsSet, //定义列
            "ajax": async function(data, callback, settings) {
                var page = [{
                    "name": "iDisplayStart",
                    "value": 1 + data.start / data.length
                }, {
                    "name": "iDisplayLength",
                    "value": data.length
                }];
                //表单序列化数据
                var _data = serialize(self.$els.form, {
                    hash: true,
                    disabled: true,
                    empty: true
                });
                _data.aoData = JSON.stringify(page);
                //发送请求
                var mchtId = JSON.parse(localStorage.getItem("id_token")).mchtId
                var result = await self.$post({
                    url: "/api/v2" + projectName_Url + "/plat/dishType/query/" + mchtId,
                    data:_data,
                    method: "POST"
                })
                if (result.respCode != "00") {
                    Midway.alert({
                        title: "操作失败",
                        content: result.content
                    })
                }
                callback({
                  recordsTotal: result.content.total || 0,
                  recordsFiltered: result.content.total || 0,
                  data: result.content.dishTypeList || []
                })
            }
        });


        $(self.$el).on("click", ".edit", function() {
            var Row = $(this).closest('tr').get(0);
            let dataArray = JSON.parse(JSON.stringify(dataTable.row(Row).data()));
            self.item = dataArray;
           //修改弹框里的上级菜单类型
            self.$post({
                    url: "/api/v2" + projectName_Url + "/plat/dishType/queryname/"+ dataArray.mchtId,
                    method: "GET"
            }).then(response => {
                    let _array = [];
                    if(response.content.dishTypeNameList != null){
                      for(let i=0;i<response.content.dishTypeNameList.length;i++){
                          _array.push({value:response.content.dishTypeNameList[i].typeId,key:response.content.dishTypeNameList[i].typeName});
                      }
                    }
                    _array.push({value:"0",key:"无"});
                    self.$set("columnsSet[3].options",_array)
//                     dataArray.updTypeName = self._array.find(data => data.key == dataArray.typeUpdId).value;
//                    self.item = dataArray;
            }, response => {
            });

            //编辑框验证、保存、提交
            $(self.$els.mform).validate(self.item.valdate = {
                async submitHandler() {
                    var form = self.$els.mform;
                    var _data = serialize(form, { hash: true, disabled:true, empty:true });
                    _data.mchtId = self.item.mchtId
                    _data.typeUpdId = self.item.typeUpdId
                    var result = await self.$post({
                        url: "/api/v2" + projectName_Url + "/plat/dishType/" +self.item.typeId,
                        data: _data,
                        method: "PUT"
                    });
                    Midway.alert({title:"操作提示",content:result.errorInfo})

                    dataTable.ajax.reload(null, false);
                    $(self.$els.modal).modal('hide');
                    self.resetBindDrag()
                },
                  rules: {
                      mchtName:{
                        required:true
                      },
                      typeId:{
                        required:true
                      },
                      typeName:{
                        required:true,
                        maxlength:10
                      }
                }
            });
            $(self.$els.modal).modal('show');
        });

        $(self.$el).on("click", ".delete", async function() {
            var Row = $(this).closest('tr').get(0);
            var typeName = dataTable.row(Row).data().typeName;
            var mchtId = dataTable.row(Row).data().mchtId;
            var typeId = dataTable.row(Row).data().typeId;
            var result = await Midway.confirm({
                title: "删除商品类型",
                content: "是否要删除商品类型:" + typeName + "?"
            })
            var result = await self.$post({
              url: "/api/v2" + projectName_Url + "/plat/dishType/"+ mchtId+"/"+ typeId,
              method: "DELETE"
            });
            Midway.alert({title:"操作提示",content:"删除成功"})
            dataTable.ajax.reload();
        });
    },
    beforeDestroy() {
        $(this.$el).off("click")
    }
}
</script>
